/*2S7LXljdWdGhrCxZ1MFl4i0/jcYg0CI/M/l35xRmsHHDM270ypZGxQFjXbKKRAXA*/
import React, { Component } from 'react';
import { createPage, ajax, toast, getMultiLang, createPageIcon, base, useJS } from 'nc-lightapp-front';
import { pageInfoClick, initTemplate, afterEvent, headerButtonClick } from './events';
import './index.less';
import { APPCODE, PAGE_CODE, LIST_IDS, ACTION, DATA_SOURCE, PKNAME } from '../consts';
import { cp2othersFun, mv2sortFun, linkToCard, checkMultiCode } from '../utils';
import ReferLoader from '../../../public/ReferLoader/index.js';
import getDefaultAccountBook from '../../../public/components/getDefaultAccountBook.js';
import TransdefCacheUtil from '../utils/TransdefCacheUtil';
import { commonApi } from '../../../public/common/actions';
import CopyCheckModal from '../../../public/components/CopyCheckModal';
import TransSortModal from '../containers/TransSortModal';
import AccountingBookModal from '../containers/AccountingBookModal';
import HeaderArea from '../../../public/components/HeaderArea';
const {EmptyAreaTip} = base;
let tableid = LIST_IDS.TABLE_ID;
let pageCode = PAGE_CODE.LIST;
let accbookRefCode = 'uapbd/refer/org/AccountBookTreeRef/index.js';

useJS.setConfig({
	'uap/common/components/ExcelOutput/index': "../../../../uap/common/components/ExcelOutput/index.js",
	'uap/common/components/excelImportconfig/index': "../../../../uap/common/components/excelImportconfig/index.js"
})

let SyncTree = useJS(["uap/common/components/ExcelOutput/index", 'uap/common/components/excelImportconfig/index'],function(ExcelOutput, excelImportconfig){
return class SyncTree extends Component {
	constructor(props) {
		super(props);
		this.cacheUtil = new TransdefCacheUtil(this.props.ViewModel);
		let state = this.cacheUtil.getListState();
		this.excelImportconfig = excelImportconfig;
		if (state) {
			this.state = state;
		} else {
			this.state = {
				pk_accountingbook: '',
				bookname: '',
				bookcode: '',
				selectedNode: '',
				pk_org: '',
				pk_transsort: '',
				showCopyCheckModal: false,
				repeatData: null,
				noRepeatArr: [],
				transsortModalShow: false,
				accbookModalShow: false, // 控制 复制到 弹框是否显示
				cardEmpty: false, //树空省适配 右半部分是否显示提示卡片
            	rightEmptyDom: false, //右半部分是否显示默认内容
				json:{}
			};
		}
		this.ShowDisable = true;
		this.props = props;
		let { form, button, table, search, syncTree } = this.props;
		let { setSyncTreeData } = syncTree;
		this.setSyncTreeData = setSyncTreeData; //设置树根节点数据方法
		this.treeId = 'transferDef'
		props.use.table(tableid);
	}

	componentDidMount() {}

	componentWillMount(){
		/* 加载多语资源 */
		let callback = (json, status, inlt) => {
			if(status){
				this.setState({json, inlt}, () => {
					initTemplate.call(this, this.props);
					this.initPage();
				});
			}else{
			}
		}
		getMultiLang({moduleId:['20020SDTRD', 'publiccommon'], domainName:'gl', callback});
	}

	initPage = () => {
		let page = this;
		let { pk_accountingbook, bookname, bookcode, pk_org } = page.state;
		if (!pk_accountingbook) {
			getDefaultAccountBook(page.props.getSearchParam('c')).then((defaultBook) => {
				if (defaultBook && defaultBook.value) {
					pk_accountingbook = defaultBook.value;
					bookname = defaultBook.display;
					page.cacheUtil.setSelectAccBook({pk_accountingbook, name:bookname});
					page.setState({ pk_accountingbook, bookname, bookcode }, () =>{
						page.loadTreeData();
						page.updateContexInfo();
					});
				} else {
					this.setState({
						cardEmpty: true,
						rightEmptyDom: false
					})
				}
			});
		} else {
			page.loadTreeData();
		}
	}

	/**
	 * 更新环境信息
	 */
	updateContexInfo = () => {
		let page = this;
		let {pk_org, pk_accountingbook} = page.state;
		commonApi.queryBookCombineInfo({
			data:pk_accountingbook,
			success: (res) => {
				if (res.success) {
					pk_org = res.data.unit.value;
				}
				page.setState({ pk_org });
			}
		})
	}

	loadTreeData(callback) {
		//加载树数据
		const node = [];
		let { pk_accountingbook, selectedNode } = this.state;
		let chacheSelectNode = this.cacheUtil.getSelectNode();
		if (pk_accountingbook) {
			let factorRoot = [
				{
					title: this.state.json['20020SDTRD-000012'],/* 国际化处理： 结转分类*/
					refname: this.state.json['20020SDTRD-000012'],/* 国际化处理： 结转分类*/
					refpk: 'root',
					innercode: '',
					nodeData: {},
					children: []
				}
			];
			const data = this.cacheUtil.getTransSort(pk_accountingbook);
			if (data) {
				if (data.children) {
					data.children.map((item) => {
						node.push(item);
					});
					factorRoot[0].children = node;
					this.props.syncTree.setSyncTreeData(this.treeId, factorRoot);
					this.props.syncTree.openNodeByPk(this.treeId, 'root')
				}
			} else {
				ajax({
					loading: true,
					url: ACTION.QRY_TRANS_SORT,
					data: { pk_accountingbook },
					success: (res) => {
						let { success, error, data } = res;
						if (success) {
							this.dealTreeData(data);
							this.cacheUtil.setTransSort(pk_accountingbook, data);
							if (data && data.children) {
								let joinCodeAndName = function(node){
									if(node){
										node.title = node.innercode + " " + node.refname;
										node.refname = node.innercode + " " + node.refname;
										if(node.children){
											node.children.map((item) => {
												joinCodeAndName(item);
												return item;
											});
										}
									}
								}

								data.children.map((item) => {
									joinCodeAndName(item);
									node.push(item);
								});
							}
							if(callback && typeof callback == 'function'){
								callback(data);
							}
						} else {
							toast({ content: error.message });
						}
						factorRoot[0].children = node;
						this.props.syncTree.setSyncTreeData(this.treeId, factorRoot);
						this.props.syncTree.openNodeByPk(this.treeId, 'root')
					}
				});
			}
			if(chacheSelectNode){
				this.props.syncTree.setNodeSelected(this.treeId, chacheSelectNode.refpk)
				this.updateAddRefreshBtnState(chacheSelectNode);
				//setSyncTreeData会选中第一个节点执行onSelectEve,若缓存的不是第一个节点右表显示不对
				this.onSelectEve('', chacheSelectNode); 
			}
		}
		this.setState({
			cardEmpty: false,
			rightEmptyDom: true
		})
	}

	
	/**
	 * 清除列表数据
	 */
	clearTableData = () => {
		let page = this;
		page.props.table.setAllTableData(tableid, { rows: [] });
	};

	// 树节点 点击事件
	onSelectEve = (pk, item) => {
		this.setState({
			showHideForm: true
		});
		this.cacheUtil.setSelectNode(item);
		this.treeNode = item;
		this.updateAddRefreshBtnState(item);
		let that = this;
		let { pk_transsort, pk_accountingbook, selectedNode } = this.state;
		selectedNode = item.refpk;
		pk_transsort = item.refpk;
		this.setState({ pk_transsort, selectedNode, cardEmpty: false, rightEmptyDom: true });
		var param = {
			pk_accountingbook: pk_accountingbook,
			pk_transsort: item.refpk,
			pagecode: pageCode
		};
		ajax({
			loading: true,
			url: '/nccloud/gl/voucher/queryTransDef.do',
			data: param,
			success: (res) => {
				let { success, data } = res;
				if (success) {
					if (data && data[tableid]) {
						that.props.table.setAllTableData(tableid, res.data[tableid]);
					} else {
						that.props.table.setAllTableData(tableid, { rows: [] });
					}
				}
			},
			error: function(res) {
				toast({content:res.message, color:'warning'});
			}
		});
	};
	//更新按钮状态
	updateButtonStatus() {
	}

	/**
	 * 只与树节点是否末级有关系
	 */
	updateAddRefreshBtnState = (item) => {
		let btnDisable = true;
		if (item && (!item.children || item.children.length <= 0)) {
			btnDisable = false;
		}
		let btnState = {add:btnDisable};
		this.cacheUtil.setBtnState(btnState);
		this.props.button.setButtonDisabled(btnState);
	};

	updateCpMVBtnState = (props) => {
		let rows = props.table.getCheckedRows(LIST_IDS.TABLE_ID);
		let cpBtnState = props.button.getButtonDisabled('cp2others');
		let mvBtnState = props.button.getButtonDisabled('mv2sort');
		let btnState = {cp2others:cpBtnState, mv2sort:mvBtnState};
		if (rows && rows.length > 0) {
			btnState.update = false;
			btnState.delete = false;
			if (cpBtnState || mvBtnState) {
				btnState.cp2others = false;
				btnState.mv2sort = false;
			}
		} else {
			btnState.update = true;
			btnState.delete = true;
			if (!cpBtnState || !mvBtnState) {
				btnState.cp2others = true;
				btnState.mv2sort = true;
			}
		}
		this.cacheUtil.setBtnState(btnState);
		props.button.setButtonDisabled(btnState);
	};

	/**
     * 处理树数据
     * @param data
     * @returns {*}
     */
	dealTreeData(data) {
		let deleteDataChildrenProp = function(node) {
			if (!node.children || node.children.length == 0) {
				delete node.children;
			} else {
				node.isLeaf = false;
				node.children.forEach((e) => {
					deleteDataChildrenProp(e);
				});
			}
		};
		if (data) {
			if (data.children) {
				data.children.forEach((e) => {
					deleteDataChildrenProp(e);
				});
			}
		}
		return data;
	}

	clearTree() {}

	/**
	 * 复制到 核算账簿弹框 确定
	 * v ：复制到的核算账簿
	 */    setBtnState(){

    }
	handleCp2others = (v) => {
		let showFlag = true
		let pk_accountingbooks = [];
		if (v) {
			v.map((item) => {
				pk_accountingbooks.push(item.refpk);
			});
		}
		if(pk_accountingbooks.length>0){
			this.checkMultiCodeBeforeAction(pk_accountingbooks);
			showFlag = false
		} else {
			toast({content:this.state.json['20020SDTRD-000009'], color:'warning'})
			/* 国际化处理： 请选择核算账簿*/
		}
		this.setState({
			accbookModalShow: showFlag
		})
	};

	/**
	 * 校验是否有重复数据
	 */
	checkMultiCodeBeforeAction = (pk_accountingbooks) => {
		let page = this;
		let codes = page.getCheckedCodes();
		let needCp2Arr = []; /* 需要复制到的账簿pk */
		checkMultiCode(page, pk_accountingbooks, codes, (data) => {
			if (!data || data.length === 0) {
				let transdefs = page.getCheckedIds();
				cp2othersFun(page, transdefs, pk_accountingbooks, (res) => {
					if (res.success) {
						toast({ content: page.state.json['20020SDTRD-000001'] });/* 国际化处理： 复制完成！*/
					}
				});
			} else {
				let repeat_pks = data.map(item => item.pk_accountingbook)
				pk_accountingbooks.map((item,index)=>{
					if(!repeat_pks.includes(item)){
						needCp2Arr.push(item);
					}
				})
				page.setState({
					repeatData: data,
					noRepeatArr: needCp2Arr,
					showCopyCheckModal: true
				});
			}
		});
	};

	/**
	 * 复制到校验弹框 确定
	 * @param {*} data //选中的需要覆盖的信息
	 */
	handleCopyCheckOK(data){
		let page = this;
		let transdefs = this.getCheckedIds();
		let { noRepeatArr } = page.state;
		let selfArr = [];
		if (data && data.length > 0) {
			data.map((item, index) => {
				selfArr.push(item.pk_accountingbook);
			});
		}
		let newPkrefs = noRepeatArr.concat(selfArr);
		cp2othersFun(page, transdefs, newPkrefs, (res) => {
			if (res.success) {
				toast({ content: page.state.json['20020SDTRD-000001'] });/* 国际化处理： 复制完成！*/
			}
		});
		this.setState({
			showCopyCheckModal: false
		});
	}

	handleMv2sort = (data) => {
		let page = this;
		let ids = this.getCheckedIds();
		let pk_transsort = data.pk_transsort;
		let id = '';
		let successflag = false;
		if (ids) {
			//id = ids[0];
			ids.forEach((id) => {
				mv2sortFun(page, id, pk_transsort, (res) => {
					if (res.success) {
						successflag =true;
					}else{
						successflag =false;
					}
				});
			});

			toast({ content: page.state.json['20020SDTRD-000002'] });/* 国际化处理： 移动完成*/
			let indexs = page.getCheckedIndex();
			page.props.table.deleteTableRowsByIndex(LIST_IDS.TABLE_ID, indexs);
		}	
	};

	/**
	 * 获取选中行code
	 */
	getCheckedCodes = () => {
		let rows = this.props.table.getCheckedRows(LIST_IDS.TABLE_ID);
		if (rows) {
			let codes = [];
			rows.map((row) => {
				codes.push(row.data.values.transferno.value);
			});
			return codes;
		}
	};
	/**
	 * 获取选中行ID
	 */
	getCheckedIds = () => {
		let rows = this.props.table.getCheckedRows(LIST_IDS.TABLE_ID);
		if (rows) {
			let ids = [];
			rows.map((row) => {
				ids.push(row.data.values.pk_transfer.value);
			});
			return ids;
		}
	};

	getCheckedIndex = () => {
		let rows = this.props.table.getCheckedRows(LIST_IDS.TABLE_ID);
		if (rows) {
			let indexs = [];
			rows.map((row) => {
				indexs.push(row.index);
			});
			return indexs;
		}
	};

	onRowDoubleClick = (record, index, props, e) => {
		let page = this;
		linkToCard(this, {
			status: 'browse',
			id: record.pk_transfer.value,
		});
	};

	/**
	 * 切换核算账簿回调
	 */
	onChangeBook = (v) => {
		let props = this.props;
		if (!v || !v.refpk) {
			return;
		}
		let btnState = {refresh:false};
		this.cacheUtil.setBtnState(btnState);
		props.button.setButtonDisabled(btnState);
		let { pk_accountingbook, bookname, bookcode } = this.state;
		pk_accountingbook = v.refpk;
		bookname = v.refname;
		bookcode = v.refcode;
		this.cacheUtil.setSelectAccBook({pk_accountingbook, name:bookname});
		this.setState({ pk_accountingbook, bookname, bookcode }, () => {
			this.loadTreeData();
			this.clearTableData();
			this.updateContexInfo();
		});
	};

	handleMv2sortConfirm = (data) => {
		let page = this;
		let { transsortModalShow } = page.state;
		transsortModalShow = false;
		page.setState({ transsortModalShow });
		page.handleMv2sort(data);
	};
	render() {
		let page = this;
		const { table, button, syncTree, DragWidthCom } = this.props;
		let props = page.props;
		const { createSimpleTable } = table;
		const { createButtonApp } = button;
		let { createSyncTree } = syncTree;
		let { transsortModalShow, accbookModalShow, pk_accountingbook, json, inlt, cardEmpty, rightEmptyDom } = page.state;
		return (
			<div className="nc-bill-tree-table">
				<HeaderArea 
					title = {this.props.getSearchParam('n')} /* 自定义转账定义 */
					searchContent = {
						<div className="main-org">
							<ReferLoader
								tag="accountingbook"
								fieldid='accountingbook'
								refcode={accbookRefCode}
								isMultiSelectedEnabled={false}
								showGroup={false}
								showStar = {true}
								showInCludeChildren={false}
								value={{
									refname: this.state.bookname,
									refpk: this.state.pk_accountingbook,
									refcode: this.state.bookcode
								}}
								isMultiSelectedEnabled={false}
								disabledDataShow={true}
								queryCondition={() => {
									let condition = {
										TreeRefActionExt: 'nccloud.web.gl.ref.AccountBookRefSqlBuilder',
										appcode: APPCODE,
										"isDataPowerEnable": false
									};
									condition.appcode = props.getSearchParam('c');
									return condition;
								}}
								onChange={this.onChangeBook}
							/>
						</div>
					}
					btnContent = {createButtonApp({
						area: 'page_header',
						onButtonClick: headerButtonClick.bind(this)
					})}
				/>
				
				<div className="tree-table">
					<DragWidthCom
						defLeftWid={'280px'}
						leftDom={
							<div className="tree-area">
								{createSyncTree({
									treeId: this.treeId,
									showLine: true,
									selectedForInit: true, //默认选中第一个子节点
									needSearch: false, //是否需要查询框，默认为true,显示。false: 不显示
									needEdit: false, //是否需要编辑节点功能，默认为true,可编辑；false：不可编辑
									onSelectEve: this.onSelectEve.bind(this) //选择节点回调方法
								})}
							</div>
						}
						rightDom={
									createSimpleTable('pk_transfer', {
										//列表区
										onAfterEvent: afterEvent,
										selectedChange: this.updateButtonStatus.bind(this), // 选择框有变动的钩子函数
										statusChange: this.updateButtonStatus.bind(this),
										handlePageInfoChange: pageInfoClick,
										showCheck: true,
										showIndex: true,
										onRowDoubleClick: this.onRowDoubleClick.bind(this),
										onSelected: () => {
											this.updateCpMVBtnState(this.props);
										},
										onSelectedAll: () => {
											this.updateCpMVBtnState(this.props);
										},
										pkname: PKNAME,
										dataSource: DATA_SOURCE,
										componentInitFinished: (v1, v2) => {
										},
										adaptionHeight: true  //表格是否自适应高度，占满屏幕
									})
						}
					/>
				</div>
				<CopyCheckModal
					visible={this.state.showCopyCheckModal}
					repeatData={this.state.repeatData}
					handleCopyCheckOK={this.handleCopyCheckOK.bind(this)}
					handleCancel={() => {
						this.setState({
							showCopyCheckModal: false
						});
					}}
				/>

				<TransSortModal
					pk_accountingbook={pk_accountingbook}
					show={transsortModalShow}
					onConfirm={this.handleMv2sortConfirm}
					json={json}
					onClose={() => {
						transsortModalShow = false;
						page.setState({ transsortModalShow });
					}}
				/>
				<AccountingBookModal
					show={accbookModalShow}
					context={{ appcode: props.getSearchParam('c') }}
					onConfirm={this.handleCp2others}
					json={json}
					inlt={inlt}
					onClose={() => {
						accbookModalShow = false;
						page.setState({ accbookModalShow });
					}}
				/>
				<ExcelOutput
					{...Object.assign(page.props)}
					moduleName="gl" //模块名
					billType="GLTD" //单据类型
					// billType="C0" //单据类型
					selectedPKS={this.getCheckedIds()}
					appcode={APPCODE}
					pagecode={'20020SDTRD_EXPORT'}
					referVO={{ignoreTemplate:false}}
				/>
			</div>
		);
	}
}
})
SyncTree = createPage({})(SyncTree);
export default SyncTree;

/*2S7LXljdWdGhrCxZ1MFl4i0/jcYg0CI/M/l35xRmsHHDM270ypZGxQFjXbKKRAXA*/